<template>
	<view class="container">
		<!-- 模式切换 -->
		<view class="mode-switch">
			<button :class="mode === 'region' ? 'active' : ''" @click="mode = 'region'">
				地区选址
			</button>
			<button :class="mode === 'map' ? 'active' : ''" @click="mode = 'map'; initMap()">
				地图选址
			</button>
		</view>

		<view class="form-container">
			<!-- 联系人信息（两种模式共用） -->
			<view class="form-item">
				<text class="label">联系人</text>
				<input v-model="form.contactName" placeholder="请输入联系人姓名" />
			</view>

			<view class="form-item">
				<text class="label">联系电话</text>
				<input v-model="form.contactPhone" placeholder="请输入联系电话" type="number" />
			</view>

			<!-- 地区选址模式 -->
			<view v-if="mode === 'region'">
				<!-- 省市区选择器 -->
				<view class="form-item">
					<text class="label">所在地区</text>
					<picker mode="multiSelector" :range="regionData" :value="regionIndex" @change="handleRegionChange"
						@columnchange="handleColumnChange">
						<view class="picker">
							{{ form.region || '请选择省市区' }}
						</view>
					</picker>
				</view>

				<!-- 详细地址 -->
				<view class="form-item">
					<text class="label">详细地址</text>
					<input v-model="form.addressDetail" placeholder="请输入详细地址" @input="debouncedAddressSearch" />
				</view>

				<!-- 定位按钮 -->
				<view class="location-actions">
					<button type="primary" plain @click="getCurrentLocation">获取当前位置</button>
				</view>

				<!-- 地区模式地图容器（H5用百度地图，App用原生map） -->
				<view class="map-container" :class="{ 'app-map-container': isApp }">
					<div v-if="isH5" id="region-map" class="baidu-map"></div>
					<map v-else id="region-map-native" :latitude="form.latitude" :longitude="form.longitude"
						:markers="markers" :show-location="true" @regionchange="handleMapRegionChange"
						style="width: 100%; height: 100%;">
					</map>
				</view>

				<!-- 地区模式地址搜索遮罩层与列表 -->
				<view v-if="showAddressList" class="address-mask" @click="showAddressList = false"></view>
				<view v-if="showAddressList" class="address-list-popup">
					<view class="address-list-header">
						<text class="list-title">地址候选</text>
						<text class="close-btn" @click="showAddressList = false">×</text>
					</view>
					<scroll-view class="address-list-scroll" scroll-y>
						<view v-if="isAddressSearching" class="search-loading">
							<view class="loading-spinner"></view>
							<text>正在搜索...</text>
						</view>
						<view v-if="!isAddressSearching && addressSearchResults.length === 0" class="search-empty">
							<text>没有找到相关地址，请尝试其他关键词</text>
						</view>
						<view v-for="(item, index) in addressSearchResults" :key="item.uid || index"
							class="address-item" @click="selectAddressInRegion(item)">
							<text class="title">{{ item.name }}</text>
							<text class="detail">{{ item.address }}</text>
						</view>
					</scroll-view>
				</view>
			</view>

			<!-- 地图选址模式 -->
			<view v-if="mode === 'map'" class="map-mode-container">
				<!-- 地图顶部栏 -->
				<view class="map-header" :class="{ 'app-map-container': isApp }">
					<text class="city">{{ currentCity || '定位中...' }}</text>
					<view class="search-box">
						<input v-model="mapSearchKeyword" placeholder="搜索地址" @input="debouncedMapSearch" />
						<button @click="mapSearch; showAroundList = true">搜索</button>
					</view>
				</view>

				<!-- 实时地址显示栏 -->
				<view class="real-time-address" v-if="form.region || form.addressDetail">
					<text class="label">当前地址：</text>
					<text class="content">{{ form.region }} {{ form.addressDetail }}</text>
				</view>

				<!-- 地图模式容器（H5用百度地图，App用原生map） -->
				<view class="map-container">
					<div v-if="isH5" id="full-map" class="baidu-map"></div>
					<map v-else id="full-map-native" :latitude="form.latitude" :longitude="form.longitude"
						:markers="markers" :show-location="true" @regionchange="handleMapRegionChange"
						@tap="handleMapDirectTap" style="width: 100%; height: 100%;">
					</map>
				</view>

				<!-- 周边地址列表 -->
				<view v-if="showAroundList" class="around-mask" @click="showAroundList = false"></view>
				<view v-if="showAroundList" class="around-addresses-popup">
					<view class="around-header">
						<text class="list-title">周边地址</text>
						<text class="close-btn" @click="showAroundList = false">×</text>
					</view>
					<scroll-view class="around-scroll" scroll-y>
						<view v-if="isSearching" class="search-loading">
							<view class="loading-spinner"></view>
							<text>正在搜索...</text>
						</view>
						<view v-if="!isSearching && aroundAddresses.length === 0 && mapSearchKeyword"
							class="search-empty">
							<text>没有找到相关地址，请尝试其他关键词</text>
						</view>
						<view v-for="(item, index) in aroundAddresses" :key="item.uid || index" class="address-item"
							@click="selectAroundAddress(item)">
							<text class="title">{{ item.name }}</text>
							<text class="detail">{{ item.address }}</text>
						</view>
						<view v-if="!isSearching && aroundAddresses.length === 0 && !mapSearchKeyword"
							class="empty-tip">
							请在搜索框输入关键词查找地址
						</view>
					</scroll-view>
				</view>
			</view>

			<!-- 设为默认地址（两种模式共用） -->
			<view class="default-address">
				<checkbox-group @change="toggleDefault">
					<label>
						<checkbox :checked="form.isDefault" />设为默认地址
					</label>
				</checkbox-group>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-btn">
			<button type="primary" @click="submitForm">保存地址</button>
		</view>
	</view>
</template>

<script>
	import {
		get,
		post,
		put
	} from '@/utils/request'
	import regionData from '@/utils/region-data.js'
	import {
		debounce
	} from 'lodash'
	import mapAk from '@/config/map-ak.js'
	// 环境判断
	const isH5 = process.env.UNI_PLATFORM === 'h5'
	const provinces = regionData.provinces.map(p => ({
		name: p.name,
		id: p.id,
		longitude: p.longitude,
		latitude: p.latitude
	}))
	const cities = {}
	const areas = {}
	regionData.provinces.forEach(province => {
		const cityList = regionData.cities[province.id] || []
		cities[province.id] = cityList.map(city => ({
			name: city.name,
			id: city.id,
			longitude: city.longitude,
			latitude: city.latitude
		}))
		cityList.forEach(city => {
			const areaList = regionData.areas[city.id] || []
			areas[city.id] = areaList.map(area => ({
				name: area.name,
				id: area.id,
				longitude: area.longitude,
				latitude: area.latitude
			}))
		})
	})
	const getRegionData = (provinceIdx = 0, cityIdx = 0) => {
		const province = provinces[provinceIdx]
		const cityList = cities[province.id] || []
		const city = cityList[cityIdx] || {}
		const areaList = areas[city.id] || []
		return [
			provinces.map(p => p.name),
			cityList.map(c => c.name),
			areaList.map(a => a.name)
		]
	}

	export default {
		data() {
			return {
				mode: 'region',
				isH5,
				form: {
					id: null,
					contactName: '',
					contactPhone: '',
					region: '',
					addressDetail: '',
					isDefault: false,
					regionId: '',
					province: '',
					city: '',
					district: '',
					longitude: 116.397128, // 默认北京
					latitude: 39.916527,
				},
				// 地图标记点（App端）
				markers: [{
					id: 1,
					latitude: 39.916527,
					longitude: 116.397128,
					width: 30,
					height: 30,
					iconPath: '/static/images/marker.png'
				}],
				currentCity: '',
				mapSearchKeyword: '',
				aroundAddresses: [],
				isSearching: false,
				showAroundList: false,
				regionData: getRegionData(),
				regionIndex: [0, 0, 0],
				mapInstance: null, // H5百度地图实例
				markerInstance: null, // H5百度地图标记
				isLocating: false,
				showAddressList: false,
				addressSearchResults: [],
				isAddressSearching: false
			}
		},
		onLoad(options) {
			if (isH5) {
				window.BMAP_PROTOCOL = window.location.protocol === 'https:' ? 'https' : 'http'
			}
			// 初始化标记点位置
			this.updateMarkerPosition()
			if (options.id) {
				this.loadAddressDetail(options.id)
			} else {
				// 延迟定位避免初始化冲突
				setTimeout(() => this.getCurrentLocation(), 500)
			}
		},
		onReady() {
			// H5端初始化地图
			if (isH5 && this.mode === 'map') {
				this.initMap()
			}
		},
		watch: {
			// 模式切换时，H5端重新初始化地图
			mode(newVal) {
				if (isH5 && newVal === 'map') {
					this.initMap()
				}
			}
		},
		methods: {
			// 更新标记点位置（App端）
			updateMarkerPosition(longitude, latitude) {
				if (!isH5) {
					const lng = longitude || this.form.longitude
					const lat = latitude || this.form.latitude
					if (lng && lat) {
						this.markers = [{
							...this.markers[0],
							longitude: lng,
							latitude: lat
						}]
					}
				}
			},

			// 初始化地图（H5端）
			async initMap() {
				if (!isH5) return

				try {
					uni.showLoading({
						title: '地图加载中...'
					})
					const BMap = await this.initBaiduMap()
					const mapId = this.mode === 'region' ? 'region-map' : 'full-map'

					// 确定地图中心点
					let centerPoint
					if (this.form.longitude && this.form.latitude) {
						centerPoint = new BMap.Point(this.form.longitude, this.form.latitude)
					} else if (this.form.region) {
						const regionPoint = this.getRegionCenterPoint()
						centerPoint = regionPoint ? new BMap.Point(regionPoint.longitude, regionPoint.latitude) :
							new BMap.Point(116.397128, 39.916527)
					} else {
						centerPoint = new BMap.Point(116.397128, 39.916527)
					}

					this.mapInstance = new BMap.Map(mapId, {
						enableMapClick: false
					})
					this.mapInstance.centerAndZoom(centerPoint, this.mode === 'map' ? 16 : 14)
					this.mapInstance.enableScrollWheelZoom(true)

					// 创建标记
					this.markerInstance = new BMap.Marker(centerPoint)
					this.mapInstance.addOverlay(this.markerInstance)

					// 绑定H5端地图事件
					if (this.mode === 'map') {
						this.mapInstance.addEventListener('dragend', () => this.handleMapDragEnd())
						this.mapInstance.addEventListener('click', (e) => this.handleMapTap(e))
					}
					uni.hideLoading()
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
					console.error('H5地图初始化失败：', e)
				}
			},

			// H5百度地图SDK加载
			initBaiduMap() {
				return new Promise((resolve, reject) => {
					if (window.BMap) return resolve(window.BMap)
					if (document.getElementById('baidu-map-script')) {
						document.getElementById('baidu-map-script').remove()
					}
					const script = document.createElement('script')
					script.id = 'baidu-map-script'
					script.type = 'text/javascript'
					script.src = `https://api.map.baidu.com/api?v=3.0&ak=${mapAk.baidu.h5}&callback=baiduMapReady`
					script.onerror = () => reject(new Error('百度地图SDK加载失败'))
					window.baiduMapReady = () => resolve(window.BMap)
					document.head.appendChild(script)
					setTimeout(() => reject(new Error('百度地图加载超时')), 5000)
				})
			},

			// 地区选择变化（省市区选择器）
			handleRegionChange(e) {
				const [provinceIdx, cityIdx, areaIdx] = e.detail.value
				this.regionIndex = e.detail.value
				const province = this.regionData[0][provinceIdx] || ''
				const city = this.regionData[1][cityIdx] || ''
				const area = this.regionData[2][areaIdx] || ''

				const regionParts = [province, city, area].filter(Boolean)
				this.form = {
					...this.form,
					province,
					city,
					district: area,
					region: regionParts.join(' '),
					addressDetail: ''
				}

				this.setRegionCoordinates(province, city, area)
			},

			// 根据地区设置经纬度
			setRegionCoordinates(province, city, area) {
				const provinceItem = provinces.find(p => p.name === province)
				if (!provinceItem) return

				let cityItem = null
				if (city) {
					const cityList = cities[provinceItem.id] || []
					cityItem = cityList.find(c => c.name === city)
				}

				if (area && cityItem) {
					const areaList = areas[cityItem.id] || []
					const areaItem = areaList.find(a => a.name === area)
					if (areaItem && areaItem.longitude && areaItem.latitude) {
						this.form.longitude = areaItem.longitude
						this.form.latitude = areaItem.latitude
						this.updateMarkerPosition(areaItem.longitude, areaItem.latitude)
						if (isH5 && this.mapInstance) {
							const point = new BMap.Point(areaItem.longitude, areaItem.latitude)
							this.mapInstance.panTo(point)
							this.markerInstance?.setPosition(point)
						}
						return
					}
				}

				// 若未获取到区域坐标，提示手动调整
				this.form.longitude = null
				this.form.latitude = null
				this.updateMarkerPosition()
				/* 	if (area) {
						uni.showToast({
							title: '未获取到区域定位，请手动选择位置',
							icon: 'none'
						})
					} */
			},

			// 省市区选择器列变化
			handleColumnChange(e) {
				const {
					column,
					value
				} = e.detail
				if (column === 0) {
					const province = provinces[value]
					const cityList = cities[province.id] || []
					const areaList = cityList[0] ? areas[cityList[0].id] || [] : []
					this.regionData = [
						provinces.map(p => p.name),
						cityList.map(c => c.name),
						areaList.map(a => a.name)
					]
					this.regionIndex = [value, 0, 0]
				} else if (column === 1) {
					const province = provinces[this.regionIndex[0]]
					const city = cities[province.id][value]
					const areaList = areas[city.id] || []
					this.regionData = [
						this.regionData[0],
						this.regionData[1],
						areaList.map(a => a.name)
					]
					this.regionIndex = [this.regionIndex[0], value, 0]
				}
			},

			// 获取当前位置（定位功能）
			getCurrentLocation() {
				if (this.isLocating) return
				this.isLocating = true
				uni.showLoading({
					title: '定位中...'
				})

				if (isH5) {
					this.tryH5Location()
				} else {
					this.tryAppLocation()
				}
			},

			// App端定位
			tryAppLocation() {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						this.isLocating = false
						uni.hideLoading()
						this.form.longitude = res.longitude
						this.form.latitude = res.latitude
						this.updateMarkerPosition(res.longitude, res.latitude)
						this.reverseGeocode(res.longitude, res.latitude)
					},
					fail: (err) => {
						this.isLocating = false
						uni.hideLoading()
						const errorMsg = err.errMsg.includes('auth') ? '请开启定位权限' : '定位失败，请手动选择'
						uni.showToast({
							title: errorMsg,
							icon: 'none'
						})
					}
				})
			},

			// H5端定位
			tryH5Location() {
				const nativeTimeout = setTimeout(() => this.tryBaiduLocation(), 8000)

				navigator.geolocation.getCurrentPosition(
					(position) => {
						clearTimeout(nativeTimeout)
						this.handleLocationSuccess(position.coords.longitude, position.coords.latitude)
					},
					() => {
						clearTimeout(nativeTimeout)
						this.tryBaiduLocation()
					}, {
						enableHighAccuracy: true,
						timeout: 8000,
						maximumAge: 0
					}
				)
			},

			// H5百度定位
			async tryBaiduLocation() {
				try {
					const BMap = await this.initBaiduMap()
					const geolocation = new BMap.Geolocation()
					geolocation.enableSDKLocation()
					geolocation.getCurrentPosition(
						(position) => {
							if (position.lng && position.lat) {
								this.handleLocationSuccess(position.lng, position.lat)
							} else {
								this.handleLocationFail('定位失败，请手动选择')
							}
						},
						() => this.handleLocationFail('百度定位失败，请手动选择'), {
							timeout: 8000
						}
					)
				} catch (e) {
					this.handleLocationFail('定位服务加载失败，请手动选择')
				}
			},

			// 定位成功处理
			handleLocationSuccess(longitude, latitude) {
				this.isLocating = false
				uni.hideLoading()
				this.form.longitude = longitude
				this.form.latitude = latitude
				this.updateMarkerPosition(longitude, latitude)
				if (isH5 && (this.mode === 'map' || this.mode === 'region')) {
					this.initMap()
				}
				this.reverseGeocode(longitude, latitude)
			},

			// 定位失败处理
			handleLocationFail(msg) {
				this.isLocating = false
				uni.hideLoading()
				uni.showToast({
					title: msg,
					icon: 'none'
				})
			},

			// 逆地理编码（坐标转地址）
			async reverseGeocode(longitude, latitude) {
				if (!longitude || !latitude) return
				try {
					const res = await this.$api.addressApi.reverseGeocode(longitude, latitude)
					if (res.code === 200 && res.data) {
						const regionInfo = this.parseRegionFromAddress(res.data.address) || {}
						this.currentCity = regionInfo.city || regionInfo.province
						this.form = {
							...this.form,
							province: regionInfo.province || '',
							city: regionInfo.city || '',
							district: regionInfo.district || '',
							region: [regionInfo.province, regionInfo.city, regionInfo.district].filter(Boolean)
								.join(' '),
							addressDetail: res.data.address || '',
							regionId: res.data.adcode
						}
						this.updateRegionPicker(regionInfo)
					}
				} catch (e) {
					console.error('逆地理编码失败:', e)
				}
			},

			// 地图点击事件（App端地图选址模式）
			handleMapDirectTap() {
				const mapId = 'full-map-native'
				const mapContext = uni.createMapContext(mapId, this)

				mapContext.getCenterLocation({
					success: (res) => {
						if (res.longitude && res.latitude) {
							this.updatePosition(res.longitude, res.latitude)
						}
					},
					fail: (err) => {
						console.error("获取地图中心坐标失败：", err)
					}
				})
			},

			// H5地图拖动结束事件
			handleMapDragEnd() {
				if (isH5 && this.mapInstance) {
					const center = this.mapInstance.getCenter()
					this.form.longitude = center.lng
					this.form.latitude = center.lat
					this.markerInstance.setPosition(center)
					this.reverseGeocode(center.lng, center.lat)
				}
			},

			// H5地图点击事件
			handleMapTap(e) {
				if (this.mapInstance) {
					const point = new BMap.Point(e.point.lng, e.point.lat)
					this.form.longitude = point.lng
					this.form.latitude = point.lat
					this.markerInstance.setPosition(point)
					this.mapInstance.panTo(point)
					this.reverseGeocode(point.lng, point.lat)
				}
			},

			// 更新位置信息（通用方法）
			updatePosition(longitude, latitude) {
				this.form.longitude = longitude
				this.form.latitude = latitude
				this.updateMarkerPosition(longitude, latitude)
				this.reverseGeocode(longitude, latitude)
			},

			// 地图区域变化事件（移动地图时更新中心点）
			handleMapRegionChange(e) {
				if (!isH5 && this.mode === 'map' && e.type === 'end') {
					const mapId = 'full-map-native'
					uni.createMapContext(mapId).getCenterLocation({
						success: (res) => {
							this.form.longitude = res.longitude
							this.form.latitude = res.latitude
							this.updateMarkerPosition(res.longitude, res.latitude)
							//更新表单地址信息
							this.reverseGeocode(res.longitude, res.latitude)
						},
						fail: (err) => {
							console.warn('获取地图中心坐标失败', err)
						}
					})
				}
				// 地区模式下的地图移动处理
				else if (!isH5 && this.mode === 'region' && e.type === 'end') {
					const mapId = 'region-map-native'
					uni.createMapContext(mapId).getCenterLocation({
						success: (res) => {
							this.form.longitude = res.longitude
							this.form.latitude = res.latitude
							this.updateMarkerPosition(res.longitude, res.latitude)
						}
					})
				}
			},

			// 地区模式地址搜索（防抖）
			debouncedAddressSearch: debounce(function() {
				this.searchAddressInRegionMode()
			}, 500),

			async searchAddressInRegionMode() {
				const keyword = `${this.form.region || ''} ${this.form.addressDetail}`.trim()
				if (!keyword || keyword === (this.form.region || '').trim()) {
					this.showAddressList = false
					return
				}

				this.isAddressSearching = true
				try {
					const params = {
						keyword,
						region: this.form.region || '',
						...(this.form.longitude && this.form.latitude ? {
							longitude: this.form.longitude,
							latitude: this.form.latitude,
							radius: 5000
						} : {})
					}
					const res = await this.$api.addressApi.searchAddress(params)
					this.addressSearchResults = res.code === 200 ? res.data.map(item => ({
						uid: item.uid,
						name: item.name,
						address: item.address,
						location: item.location
					})) : []
					this.showAddressList = this.addressSearchResults.length > 0
				} catch (e) {
					this.addressSearchResults = []
					this.showAddressList = false
					console.error('地区模式地址搜索失败:', e)
				} finally {
					this.isAddressSearching = false
				}
			},

			// 选择地区模式地址
			selectAddressInRegion(item) {
				this.form.addressDetail = item.address
				this.form.longitude = item.location?.lng
				this.form.latitude = item.location?.lat
				this.updateMarkerPosition(item.location?.lng, item.location?.lat)
				if (isH5 && this.mapInstance && item.location) {
					const point = new BMap.Point(item.location.lng, item.location.lat)
					this.mapInstance.panTo(point)
					this.markerInstance.setPosition(point)
				}
				this.showAddressList = false
			},

			// 地图模式搜索
			mapSearch() {
				this.searchAroundAddresses(this.mapSearchKeyword || '地址')
			},

			// 地图模式搜索（防抖）
			debouncedMapSearch: debounce(function() {
				this.searchAroundAddresses(this.mapSearchKeyword || '地址')
			}, 500),

			async searchAroundAddresses(keyword) {
				if (!this.form.longitude || !this.form.latitude) return
				this.isSearching = true
				try {
					const res = await this.$api.addressApi.searchAddress({
						keyword,
						longitude: this.form.longitude,
						latitude: this.form.latitude,
						radius: 3000
					})
					this.aroundAddresses = res.code === 200 ? res.data || [] : []
					this.showAroundList = true
				} catch (e) {
					this.aroundAddresses = []
					console.error('周边检索失败:', e)
				} finally {
					this.isSearching = false
				}
			},

			// 选择周边地址
			selectAroundAddress(item) {
				this.form.addressDetail = item.address
				this.form.longitude = item.location.lng
				this.form.latitude = item.location.lat
				this.updateMarkerPosition(item.location.lng, item.location.lat)
				if (isH5 && this.mapInstance) {
					const point = new BMap.Point(item.location.lng, item.location.lat)
					this.mapInstance.panTo(point)
					this.markerInstance.setPosition(point)
				}
				this.reverseGeocode(item.location.lng, item.location.lat)
				this.showAroundList = false
			},

			// 解析地址中的省市区信息
			parseRegionFromAddress(address) {
				for (const province of regionData.provinces) {
					if (!address.includes(province.name)) continue
					const cities = regionData.cities[province.id] || []
					for (const city of cities) {
						if (!address.includes(city.name)) continue
						const areas = regionData.areas[city.id] || []
						for (const area of areas) {
							if (address.includes(area.name)) {
								return {
									province: province.name,
									city: city.name,
									district: area.name
								}
							}
						}
					}
				}
				for (const province of regionData.provinces) {
					if (address.includes(province.name)) {
						const cities = regionData.cities[province.id] || []
						for (const city of cities) {
							if (address.includes(city.name)) {
								return {
									province: province.name,
									city: city.name,
									district: ''
								}
							}
						}
						return {
							province: province.name,
							city: '',
							district: ''
						}
					}
				}
				return null
			},

			// 更新地区选择器
			updateRegionPicker(regionInfo) {
				if (!regionInfo.province) return
				const provinceIdx = this.regionData[0].indexOf(regionInfo.province)
				if (provinceIdx >= 0) {
					this.regionIndex[0] = provinceIdx
					this.handleColumnChange({
						detail: {
							column: 0,
							value: provinceIdx
						}
					})
					if (regionInfo.city) {
						const cityIdx = this.regionData[1].indexOf(regionInfo.city)
						if (cityIdx >= 0) {
							this.regionIndex[1] = cityIdx
							this.handleColumnChange({
								detail: {
									column: 1,
									value: cityIdx
								}
							})
							if (regionInfo.district) {
								const districtIdx = this.regionData[2].indexOf(regionInfo.district)
								if (districtIdx >= 0) {
									this.regionIndex[2] = districtIdx
								}
							}
						}
					}
				}
			},

			// 加载地址详情
			async loadAddressDetail(id) {
				try {
					const res = await get(`/user/address/${id}`)
					if (res.code === 200) {
						this.form = {
							...res.data,
							addressDetail: res.data.address,
							region: res.data.regionName ||
								`${res.data.province} ${res.data.city} ${res.data.district}`
						}
						this.updateMarkerPosition()
						if (isH5 && (this.mode === 'map' || this.mode === 'region')) {
							this.initMap()
						}
					}
				} catch (e) {
					/* uni.showToast({
						title: '获取地址详情失败',
						icon: 'none'
					}) */
				}
			},

			// 设为默认地址
			toggleDefault(e) {
				this.form.isDefault = e.detail.value.length > 0
			},

			// 表单校验
			validateForm() {
				if (!this.form.contactName.trim()) {
					uni.showToast({
						title: '请输入联系人姓名',
						icon: 'none'
					})
					return false
				}
				if (!this.form.contactPhone.trim()) {
					uni.showToast({
						title: '请输入联系电话',
						icon: 'none'
					})
					return false
				}
				if (this.mode === 'region' && !this.form.region) {
					uni.showToast({
						title: '请选择所在地区',
						icon: 'none'
					})
					return false
				}
				if (!this.form.addressDetail.trim()) {
					uni.showToast({
						title: '请输入详细地址',
						icon: 'none'
					})
					return false
				}
				if (!this.form.longitude || !this.form.latitude) {
					uni.showToast({
						title: '请选择地址位置',
						icon: 'none'
					})
					return false
				}
				return true
			},

			// 提交表单
			async submitForm() {
				if (!this.validateForm()) return
				try {
					uni.showLoading({
						title: '保存中...'
					})
					if (!this.form.longitude || !this.form.latitude) {
						await this.geocodeAddress()
						if (!this.form.longitude || !this.form.latitude) {
							uni.hideLoading()
							uni.showToast({
								title: '请选择地址',
								icon: 'none'
							})
							return
						}
					}
					const customerId = this.$store.getters['user/userId']
					if (!customerId) {
						uni.hideLoading()
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						})
						setTimeout(() => uni.navigateTo({
							url: '/pages/login/login'
						}), 1000)
						return
					}
					const params = {
						...this.form,
						address: this.form.addressDetail,
						regionId: this.form.regionId,
						customerId,
						longitude: this.form.longitude,
						latitude: this.form.latitude
					}
					const res = this.form.id ?
						await this.$api.addressApi.updateAddress(params) :
						await this.$api.addressApi.addAddress(params)
					if (res.code === 200) {
						uni.showToast({
							title: '保存成功'
						})
						setTimeout(() => uni.navigateBack(), 1500)
					}
				} catch (e) {
					console.error('保存地址失败:', e)
					uni.showToast({
						title: `保存失败: ${e.message || '未知错误'}`,
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 地址转坐标
			async geocodeAddress() {
				try {
					const fullAddress = `${this.form.region} ${this.form.addressDetail}`.trim()
					if (!fullAddress) return
					const res = await this.$api.addressApi.geocode(fullAddress)
					if (res.code === 200 && res.data) {
						this.form.longitude = parseFloat(res.data.longitude)
						this.form.latitude = parseFloat(res.data.latitude)
						this.updateMarkerPosition()
						if (isH5 && this.mapInstance) {
							const point = new BMap.Point(this.form.longitude, this.form.latitude)
							this.mapInstance.panTo(point)
							this.markerInstance.setPosition(point)
						}
					}
				} catch (e) {
					console.error('地址转坐标失败:', e)
					/* 	uni.showToast({
							title: '无法获取位置信息',
							icon: 'none'
						}) */
				}
			}
		},
		onUnload() {
			// 清理H5地图实例
			if (isH5 && this.mapInstance) {
				this.mapInstance.clearOverlays()
				this.mapInstance = null
				this.markerInstance = null
			}
		}
	}
</script>

<style lang="scss">
	.container {
		padding: 20rpx;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.app-map-container {
		z-index: 1;
	}

	.app-map-container map {
		pointer-events: none;
		/* 禁止 map 拦截点击 */
	}

	// 模式切换样式
	.mode-switch {
		display: flex;
		margin-bottom: 20rpx;

		button {
			flex: 1;
			margin: 0 10rpx;
			background-color: #fff;
			color: #333;
			border: 1px solid #eee;
			font-size: 28rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 8rpx;

			&.active {
				background-color: #5eba8f;
				color: #fff;
				border-color: #5eba8f;
			}
		}
	}

	.form-container {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		overflow: visible;
	}

	.form-item {
		margin-bottom: 30rpx;

		.label {
			display: block;
			font-size: 28rpx;
			color: #666;
			margin-bottom: 10rpx;
		}

		input,
		.picker {
			height: 80rpx;
			line-height: 80rpx;
			border-bottom: 1rpx solid #eee;
			font-size: 32rpx;
			color: #333;
			width: 100%;
			box-sizing: border-box;
		}

		.picker {
			display: flex;
			align-items: center;
		}
	}

	// 地址搜索遮罩层

	.address-list-scroll,
	.around-scroll {
		max-height: calc(60vh - 100rpx);
		padding: 0 30rpx;
	}

	// 实时地址显示栏
	.real-time-address {
		width: 100%;
		padding: 15rpx 0;
		margin-bottom: 20rpx;
		background-color: #f8f9fa;
		border-radius: 8rpx;
		padding-left: 10rpx;
		box-sizing: border-box;

		.label {
			font-size: 28rpx;
			color: #666;
			font-weight: 500;
		}

		.content {
			font-size: 28rpx;
			color: #333;
			word-break: break-all;
			line-height: 1.5;
		}
	}

	.location-actions {
		display: flex;
		justify-content: space-between;
		margin: 30rpx 0;

		button {
			width: 48%;
			font-size: 28rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 8rpx;
		}
	}

	.default-address {
		margin-top: 30rpx;
		font-size: 28rpx;
		padding: 10rpx 0;
		display: flex;
		align-items: center;

		checkbox {
			transform: scale(0.8);
			margin-right: 10rpx;
		}
	}

	.submit-btn {
		padding: 0 30rpx;

		button {
			background-color: #5eba8f;
			color: #fff;
			height: 90rpx;
			line-height: 90rpx;
			font-size: 32rpx;
			border-radius: 8rpx;
			width: 100%;
		}
	}

	// 地图容器样式
	.map-container {
		width: 100% !important;
		height: 300px !important;
		min-height: 300px !important;
		overflow: visible !important;
		pointer-events: auto !important;
		position: relative;
		border-radius: 16rpx;
		margin-top: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		background-color: #e5e3df;

		.baidu-map {
			width: 100% !important;
			height: 100% !important;
		}

		z-index: 1;
	}

	// 地图模式下容器高度调整
	.map-mode-container .map-container {
		height: 400px !important;
		min-height: 400px !important;
	}

	// 地图模式样式
	.map-mode-container {
		margin-top: 20rpx;
	}

	.map-header {
		padding: 20rpx 0;
		background-color: #fff;
		display: flex;
		flex-direction: column;

		.city {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 15rpx;
		}

		.search-box {
			display: flex;
			align-items: center;

			input {
				flex: 1;
				height: 70rpx;
				background-color: #f5f5f5;
				border-radius: 35rpx;
				padding: 0 20rpx;
				font-size: 28rpx;
				border: none;
			}

			button {
				width: 120rpx;
				height: 70rpx;
				line-height: 70rpx;
				margin-left: 15rpx;
				border-radius: 35rpx;
				font-size: 28rpx;
				background-color: #5eba8f;
				color: #fff;
				border: none;
			}
		}
	}

	// 地址项样式
	.address-item {
		padding: 25rpx 0;
		border-bottom: 1rpx solid #f5f5f5;

		.title {
			font-size: 30rpx;
			color: #333;
			display: block;
		}

		.detail {
			font-size: 26rpx;
			color: #999;
			display: block;
			margin-top: 10rpx;
		}
	}

	.empty-tip {
		padding: 50rpx;
		text-align: center;
		color: #999;
		font-size: 28rpx;
	}

	// 搜索加载样式
	.search-loading {
		height: 200rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		color: #666;

		.text {
			margin-top: 15rpx;
			font-size: 28rpx;
		}
	}

	.loading-spinner {
		width: 40rpx;
		height: 40rpx;
		border: 4rpx solid rgba(94, 186, 143, 0.3);
		border-radius: 50%;
		border-top-color: #5eba8f;
		animation: spin 1s linear infinite;
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}

	.search-empty {
		height: 200rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999;
		font-size: 28rpx;
		text-align: center;
	}

	// 适配不同设备
	@media (min-width: 768px) {
		.container {
			max-width: 750px;
			margin: 0 auto;
		}

		.map-container {
			height: 500rpx !important;
		}
	}
</style>